import 'package:get/get.dart';
import 'package:yt_devops/components/yt_multi_column_picker/model/yt_multi_column_model.dart';
import 'package:yt_devops/utils/func_utils.dart';

class YtMultiColumnPickerController extends GetxController {
  MultiColumnModel data;

  List<int> defaultFocusedIndexes;

  YtMultiColumnPickerController(this.data,
      {this.defaultFocusedIndexes = const []});

  List<MultiColumnModel> firstList = [];

  List<MultiColumnModel> secondList = [];

  MultiColumnModel? secondCheckedModel;

  int firstIndex = -1;

  int secondIndex = -1;

  List<int> get firstSelectedValues => firstIndex == -1 || firstList.isEmpty
      ? []
      : [firstList[firstIndex].value];

  List get checkedValues =>
      secondCheckedModel == null ? [] : [secondCheckedModel!.value];

  initData() {
    _configDefaultInitSelectIndex();

    _configDefaultSelectedData();

    _refreshDataSource();
  }

  void _configDefaultInitSelectIndex() {
    firstIndex = secondIndex = -1;
  }

  void _refreshDataSource() {
    firstList = data.selectList;
    if (firstIndex >= 0 && firstList.length > firstIndex) {
      secondList = firstList[firstIndex].selectList;
    } else {
      secondList = [];
    }
  }

  void _configDefaultSelectedData() {
    firstList = data.selectList;

    if (!FuncUtils.isListEmpty(defaultFocusedIndexes)) {
      for (int index = 0; index < defaultFocusedIndexes.length; index++) {
        if (index == 0 && defaultFocusedIndexes[index] >= 0) {
          firstIndex = defaultFocusedIndexes[index];
        }

        if (index == 1 && firstIndex >= 0) {
          secondIndex = defaultFocusedIndexes[index];
        }
      }
    }

    if (firstIndex >= 0 && firstIndex < firstList.length) {
      secondList = firstList[firstIndex].selectList;
    }

    secondCheckedModel = secondIndex != -1 ? secondList[secondIndex] : null;
  }

  int _getInitialSelectIndex(List<MultiColumnModel>? levelList,
      [MultiColumnModel? parent]) {
    int index = -1;
    if (levelList == null || levelList.isEmpty) {
      return index;
    }

    for (MultiColumnModel entity in levelList) {
      if (entity.selected) {
        index = levelList.indexOf(entity);
        break;
      }
    }

    if (index < 0) {
      for (MultiColumnModel entity in levelList) {
        // 当上一级为多选时，当前级不应有默认焦点，
        // 例如1级为多选，不应该默认选中2级的不限
        // 否则每选中任意一个1级选项，就默认有了一个2级的不限
        if (entity.isUnLimit() &&
            parent != null &&
            parent.pickerType != MultiColumnPickerType.checkbox) {
          index = levelList.indexOf(entity);
          break;
        }
      }
    }
    return index;
  }

  onFirstSelect(int index) {
    firstIndex = index;
    _refreshDataSource();
    update();
  }

  onSecondSelect(int index, MultiColumnModel model) {
    secondIndex = index;
    secondCheckedModel = model;
    update();
  }
}
